import json
import re

from django.http import HttpResponse, Http404
from django.core.cache import cache

tel_pattern = re.compile(r'/api/code/(?P<tel>1[3-9]\d{9})')

CODE_CACHE_TIMEOUT = 60


def block_sms_middleware(get_response):
    """阻止60秒以内重复获取手机验证码的中间件"""

    def middleware(request):
        try:
            if request.path.startswith('/api/code'):
                matcher = tel_pattern.match(request.path)
                tel = matcher.group('tel')
                if cache.get(tel):
                    result = {
                        'code': 401,
                        'msg': f'请不要在{CODE_CACHE_TIMEOUT}秒内重复提交'
                    }
                    return HttpResponse(json.dumps(result), content_type='application/json; charset=utf-8')
            return get_response(request)
        except Exception:
            raise Http404('无效的请求')

    return middleware
